package com.thinklib.config;

import com.thinklib.controller.ViewController;
import com.thinklib.util.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {
	
	// 这个方法是在访问接口之前执行的，我们只需要在这里写验证登陆状态的业务逻辑，就可以在用户调用指定接口之前验证登陆状态了
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String token = request.getParameter("authorization");

		if (token != null) {
			Claims claims = JwtUtils.jwtDecryption(token);
			if (claims != null) {
				boolean thinklib = claims.getSubject().equals("thinklib.com");
				// 如果claims中没有user，表示没登陆
				if (thinklib) {
					return true;
				} else {
					return false;
				}
			}else {
				ViewController.goIndex();
			}
		}
		return false;
	}
}
